Utils = window.Utils = {}
Utils.getSetting = ->
  try
    opts = JSON.parse(window.localStorage.opts)
  catch e
    opts = {
      servers: [
        {
          name: "local"
          select: true
          url: "http://localhost:6800/jsonrpc"
        }
      ]
      downMode: "ask"
      notifyMode: "always"
      yaawURL: "http://yaaw.yky.me"
    }
  return opts
Utils.saveSetting = (opts)->
  window.localStorage.opts = JSON.stringify(opts)

Utils.bindRadioOpts = (opts, fieldName, storeName = fieldName)->
  $("[name='#{fieldName}']").click(
    ->
      opts[storeName] = $(this).val()
      Utils.saveSetting(opts);
  )
  $("[name='#{fieldName}'][value='#{opts[storeName]}']").attr("checked", true);
  return

Utils.bindTextOpts = (opts, fieldName, storeName = fieldName)->
  $("[name='#{fieldName}']").blur(
    ->
      opts[storeName] = $(this).val()
      Utils.saveSetting(opts);
  )
  $("[name='#{fieldName}']").val(opts[storeName]);
  return

Utils.getFileLength = (length) ->
  if length < 1024
    length + " byte"
  else if length < 1024 * 1024
    (length / 1024).toFixed(2) + " KiB"
  else if length < 1024 * 1024 * 1024
    (length / (1024 * 1024)).toFixed(2) + " MiB"
  else (length / (1024 * 1024 * 1024)).toFixed(2) + " GiB"  if length < 1024 * 1024 * 1024 * 1024


Utils.ajax = (method, url, params, json = true)->
  xhr = new XMLHttpRequest()
  xhr.open(method, url, false)
  try
    xhr.send(if typeof(params) isnt "string" then JSON.stringify(params) else params)
  catch e
    console.error("Utils.ajax", e)
    return
  return (if json then JSON.parse(xhr.responseText) else xhr.responseText)


Utils.fillCookies = (downInfo, cb)->
  chrome.cookies.getAll(
    {
      url: downInfo.url
    }
    (cookies)->
      downInfo.cookies = ({
      name: ck.name
      value: ck.value
      } for ck in cookies)
      cb(downInfo)
      return
  )
  return

Utils.downInfoToAria2AddUri = (downInfo)->
  headers = []
  headers.push("Referer: #{downInfo.referrer}")
  headers.push("Cookie: #{ck.name}=#{ck.value}") for ck in downInfo.cookies
  args = {
    jsonrpc: 2.0
    id: "cdhelper_download"
    method: "aria2.addUri",
    params: [
      [downInfo.url]
      {
        out: downInfo.filename
        header: headers
      }
    ]
  }
  return args

Utils.directDownload = (downInfo)->
  msgs = []
  notifyMode = Utils.getSetting().notifyMode
  for server in Utils.getSetting().servers when server.select is true
    result = Utils.ajax("post", server.url, Utils.downInfoToAria2AddUri(downInfo))
    msgResult = if result then "发送成功！" else "发送失败！"
    switch notifyMode
      when "always"
        msgs.push({title: server.name, message: msgResult})
      when "only_failure"
        if not result
          msgs.push({title: server.name, message: msgResult})
  if msgs.length > 0
    chrome.notifications.create("download_notify_" + new Date().getTime(), {
        title: "Aria2下载"
        type: "list"
      #message: "Aria2发送结果"
        iconUrl: "imgs/logo.png"
        items: msgs
      },
    ->
      return
    )
  return


